package com.datamation.swadeshi.control;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;

import com.datamation.swadeshi.control.data.FTranHedDS;
import com.datamation.swadeshi.control.data.InvHedDS;
import com.datamation.swadeshi.control.data.OrdHedDS;
import com.datamation.swadeshi.model.mapping.LoadingMapper;
import com.datamation.swadeshi.model.mapping.PreSalesMapper;
import com.google.gson.Gson;


public class UploadLoading extends AsyncTask<ArrayList<LoadingMapper>, Integer, ArrayList<LoadingMapper>> {
	
	Context context;
	ProgressDialog dialog;
	
	AsyncTaskListener taskListener;
	TaskType taskType;
	
	int totalRecords;
	
	//Shared Preferences variables 
	public static final String SETTINGS = "SETTINGS";
	public static SharedPreferences localSP;
	
	public UploadLoading(Context context, AsyncTaskListener taskListener, TaskType taskType){
		
		this.context = context;
		this.taskListener = taskListener;
		this.taskType = taskType;
		
		localSP = context.getSharedPreferences(SETTINGS,Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);
				
	}
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		dialog = new ProgressDialog(context);
		//dialog.setTitle("Uploading records");
		dialog.show();
	}
	
	@Override
	protected ArrayList<LoadingMapper> doInBackground(ArrayList<LoadingMapper>... params) {
		
		int recordCount = 0;
		publishProgress(recordCount);
		
		ArrayList<LoadingMapper> RCSList = params[0];
		totalRecords = RCSList.size();
		
		final String sp_url =localSP.getString("URL", "").toString();
		String URL="http://"+sp_url;
		
		
		
		//inserting into back-end system
		for(LoadingMapper c : RCSList){
			
			List<String> List = new ArrayList<String>();
			
			String sJsonHed = new Gson().toJson(c);
			
			List.add(sJsonHed);
			
			Log.v("## Json ##",  List.toString());
			
			try {
			// PDADBWebServiceMO
			HttpPost requestfDam = new HttpPost(URL+ "/AndroidWebServices/AndroidWebServicesRest.svc/insertFTranHed");
			StringEntity entityfDam = new StringEntity( List.toString(), "UTF-8");
			entityfDam.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
			entityfDam.setContentType("application/json");
			requestfDam.setEntity(entityfDam);
			// Send request to WCF service
			DefaultHttpClient httpClientfDamRec = new DefaultHttpClient();
			
			
			HttpResponse responsefDamRec = httpClientfDamRec.execute(requestfDam);
			HttpEntity entityfDamEntity = responsefDamRec.getEntity();
			InputStream is = entityfDamEntity.getContent();
			
			//StatusLine statusLine = responsefDamRec.getStatusLine();
		    //int statusCode = statusLine.getStatusCode();
			
			if (is != null) 
			{
				BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
			    StringBuilder sb = new StringBuilder();

			    String line = null;
			    while ((line = reader.readLine()) != null){
			        sb.append(line + "\n");
			    }
			    
			   is.close();
			  
			   String result = sb.toString();
			   String result_fDamRec = result.replace("\"", "");
			   
			   Log.e("response", "connect:" + result_fDamRec);
			  
			   if (result_fDamRec.trim().equals("200")){
					 c.setIS_SYNCED(true);
				}else {
					c.setIS_SYNCED(false);
				}
			   
			   
			}
			
			
			}catch(Exception e){
				
				e.getStackTrace();
			}
			
			++recordCount;
			publishProgress(recordCount);
		}
		
		return RCSList;
	}
	
	@Override
	protected void onProgressUpdate(Integer... values) {
		super.onProgressUpdate(values);
		dialog.setMessage("Uploading.. Loading record " + values[0] + "/" + totalRecords);
	}
	
	@Override
	protected void onPostExecute(ArrayList<LoadingMapper> RCSList) {
		
			super.onPostExecute(RCSList);
			
			for(LoadingMapper c : RCSList){
				new FTranHedDS(context).updateIsSynced(c);
			}
			dialog.dismiss();
			taskListener.onTaskCompleted(taskType);
			
		
	}

}
